package org.jiuling.email;

import org.jiuling.email.config.EmailConfig;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 电子邮件
 * @author 紫灵
 * @date 2022年08月05日 00时08分03秒
 */
public class Email {

    /** 电子邮件配置 */
    private final EmailConfig emailConfig;

    public Email(EmailConfig emailConfig) {
        this.emailConfig = emailConfig;
    }

    /**
     * 电子邮件配置
     * @return 电子邮件配置
     */
    public EmailConfig getEmailConfig() {
        return emailConfig;
    }

    /**
     * 获取电子邮件属性
     * @return 属性
     */
    private Properties getProperties(){
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", emailConfig.getProtocol()); // 连接协议
        properties.put("mail.smtp.host", emailConfig.getHost());
        properties.put("mail.smtp.port", emailConfig.getPost());
        properties.put("mail.smtp.auth", emailConfig.getAuth());
        properties.put("mail.smtp.ssl.enable", emailConfig.getEnable());
        properties.put("mail.debug", emailConfig.getDebug());
        return properties;
    }

    /**
     * 发送电子哟见
     * @param sender 发送人
     * @param recipients 接收人数组
     * @param title 标题
     * @param content 内容
     * @throws MessagingException
     */
    public void sendEmail(String sender,String[] recipients,String title,String content) throws MessagingException {
        // 得到回话对象
        Session session = Session.getInstance(getProperties());

        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(sender));

        // 接收人个数
        int recipientNum = recipients.length;
        // 接收人
        InternetAddress[] internetAddresses = new InternetAddress[recipientNum];
        for (int i = 0; i < recipientNum; i++) {
            internetAddresses[i] = new InternetAddress(recipients[i]);
        }

        // 设置收件人邮箱地址
         message.setRecipients(Message.RecipientType.TO, internetAddresses); // 多个收件人
        // 设置邮件标题
        message.setSubject(title);
        // 设置邮件内容
        message.setText(content);

        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(emailConfig.getUser(), emailConfig.getPassword()); // 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * 发送电子哟见
     * @param sender 发送人
     * @param recipient 接收人
     * @param title 标题
     * @param content 内容
     * @throws MessagingException
     */
    public void sendEmail(String sender,String recipient,String title,String content) throws MessagingException {
        String[] recipients = new String[]{recipient};
        sendEmail(sender,recipients,title,content);
    }

}
